﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing;

namespace OpenPhotoAlbum.Controls.PhotoProcessors
{
	public class NegativeImage : IPhotoProcessor
	{
		#region IPhotoProcessor Members

		public byte[] Process(byte[] input)
		{
			MemoryStream ms = new MemoryStream(input);
			Bitmap source = new Bitmap(ms);
			Bitmap canvas = new Bitmap(source.Width, source.Height);
			Bitmap temp = new Bitmap(source.Width, source.Height);

			DateTime t1 = DateTime.UtcNow;

			{
				ImageAttributes ia = new ImageAttributes();
				ColorMatrix cm = new ColorMatrix();
				cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = 0.99f;
				cm.Matrix33 = cm.Matrix44 = 1;
				cm.Matrix40 = cm.Matrix41 = cm.Matrix42 = .04f;
				ia.SetColorMatrix(cm);

				Graphics g = Graphics.FromImage(temp);
				g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, ia);
				g.Dispose();
			}
			{
				ImageAttributes ia = new ImageAttributes();
				ColorMatrix cm = new ColorMatrix();
				cm.Matrix00 =
				cm.Matrix11 =
				cm.Matrix22 = -1;
				ia.SetColorMatrix(cm);

				Graphics g = Graphics.FromImage(canvas);
				g.DrawImage(temp, new Rectangle(0, 0, temp.Width, temp.Height), 0, 0, temp.Width, temp.Height, GraphicsUnit.Pixel, ia);
				g.Dispose();
			}

			DateTime t2 = DateTime.UtcNow;
			System.Diagnostics.Debug.WriteLine(t2.Subtract(t1).TotalMilliseconds);

			ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

			//find the encoder with the image/jpeg mime-type
			ImageCodecInfo ici = null;
			foreach (ImageCodecInfo codec in codecs)
			{
				if (codec.MimeType == "image/jpeg")
					ici = codec;
			}

			EncoderParameters ep = new EncoderParameters();
			ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)90);

			MemoryStream msResult = new MemoryStream();
			canvas.Save(msResult, ici, ep);

			temp.Dispose();
			canvas.Dispose();
			source.Dispose();
			ms.Close();

			return msResult.ToArray();
		}

		#endregion
	}
}
